package com.enlighten.aio.doc.service.Impl;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.enlighten.aio.db.mapper.DocumentMapper;
import com.enlighten.aio.db.model.Document;
import com.enlighten.aio.db.model.DocumentExample;
import com.enlighten.aio.doc.service.DocumentService;
import com.x.share.mid.exception.HelperException;
import com.x.share.mid.prop.AliOSSProperties;
import com.x.share.mid.utils.AliOSSUtils;
import com.x.share.mid.utils.ToolUtil;
@Service
public class DocumentServiceImpl implements DocumentService{
	
	@Resource
	DocumentMapper documentMapper;
	@Resource
	AliOSSProperties aliOSSProperties;
	
	@Override
	public List<Document> getDocumentById(Long userId) {
		DocumentExample de = new DocumentExample();
		de.or().andUserIdEqualTo(userId);
		List<Document> list = documentMapper.selectByExampleWithBLOBs(de);
		return list;
	}

	@Override
	public List<Document> getDocument() {
		DocumentExample example = new DocumentExample();
		example.or().andAuthorityEqualTo(1);
		List<Document> list = documentMapper.selectByExampleWithBLOBs(example);
		return list;
	}

	@Override
	public boolean delDocument(Long id) {
		String ossId  = documentMapper.selectByPrimaryKey(id).getOssId();
		AliOSSUtils.removeFromOSS(aliOSSProperties, ossId);
		int num = documentMapper.deleteByPrimaryKey(id);
		if(num != 1) {
			throw new HelperException("删除文档失败");
		}
		return num > 0 ? true : false;
	}

	@Override
	public String uploadtDocument(MultipartFile file,Long userId,Integer authority) {
		int docNum=0;
		String key=null;
		try {
			key = AliOSSUtils.uploadToOSS(aliOSSProperties, file.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		Document d = new Document();
		String fileName = file.getOriginalFilename();
		String url = aliOSSProperties.getBucket() + "." + aliOSSProperties.getGateway() + "/" + key;
		String name = fileName.substring(0, fileName.indexOf("."));
		d.setName(name);
		d.setOssId(key);
		d.setCreateDate(ToolUtil.getTime(0));
		d.setUrl(url);
		d.setUserId(userId);
		d.setAuthority(authority);
		docNum = documentMapper.insertSelective(d);
		if(docNum != 1) {
			AliOSSUtils.removeFromOSS(aliOSSProperties, key);
			throw new HelperException("上传文档失败");
		}
		return url;
	}

	@Override
	public String getDoc(Long id) {
		Document doc = documentMapper.selectByPrimaryKey(id);
		return doc.getUrl();
	}
}
